/**
 * 具有默认错误处理函数的Promise
 * 当调用者未catch时，由默认错误处理函数兜底；调用者有catch时，默认错误处理函数不会执行
 */
export default class SafePromise extends Promise {
    constructor(executor, defaultErrorHandler) {
        if (typeof defaultErrorHandler !== 'function') {
            super(executor);
        } else {
            super((resolve, reject) => {
                const caughtReject = cause => {
                    let error = {
                        cause
                    };
                    reject(error);
                    setTimeout(() => {
                        if (error.cause) {
                            defaultErrorHandler(error.cause);
                        }
                    }, 10);
                }
                try {
                    executor(resolve, caughtReject);
                } catch (e) {
                    caughtReject(e);
                }
            });
        }
    }

    catch (handler) {
        return super.catch(error => {
            let cause = error.cause;
            delete error.cause;
            handler(cause);
        });
    }

}